<script setup>
const modules = import.meta.glob("@/views/**/**.vue", {eager: true});

import { getFlowDefinitionInfo, getInstanceInfo } from "@/api/v-wkf-service/wkf-space"
/**
 * 定义emit事件
 */
const emits = defineEmits([
  'update:modelValue',
  'update:hasTempSave',
])
/**
 * 定义props 属性
 */
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  dialogTitle: {
    type: String,
    default: ""
  },
  flowKey: String,
  componentUrl: String,
  paramObj: Object,
  hasTempSave: Boolean,
  //1:发起流程，2:我发起的，3:我的待办,4:我的已办
  formType: {
    type: Number,
    default: 1
  },
})

const processInfo = ref({
  processDefinitionId: '',
  process: {},
  formJson: [],
  taskId: '',
  auditedNodes: []
})

const loading = ref({
  tempLoading: false, //暂存loading
  startLoading: false, //提交loading
  passLoading: false, //通过loading
  refuseLoading: false, //驳回loading
})

const flowFormRef = ref()

const commentData = ref({
  comments: '',
})

const commentRules = ref({
  comments: [{ required: false, message: "请填写审批意见", trigger: "blur" }]
})

const commentRef = ref()

const visible = computed(
    {
      get(){
        return props.modelValue
      },
      set(val){
        emits('update:modelValue',val)
      }
    }
)


const handleData = (res) => {
  const {code, data} = res
  if (code === 200) {
    // 取最后一个key为当前流程执行节点
    const detailVoMap = data.detailVOList
    const formData = data.formData
    const keys = Object.keys(detailVoMap)
    const key = keys[keys.length-1]
    processInfo.value.auditedNodes = []
    processInfo.value.detailVoList = data.detailVOList
    processInfo.value.auditedNodes = keys.map(ele => {
      const obj = {}
      if (!['startEventNode', 'root', 'endEventNode'].includes(ele)) {
        obj.nodeId = ele
        obj.nodeName = detailVoMap[ele][0].name
        obj.commentVoList = detailVoMap[ele][0].optionVOList || []
      }
      return obj
    }).filter(ele => ele.nodeId && ele.nodeId!==detailVoMap[key][0].activityId)
    processInfo.value.processDefinitionId = data.processInstanceId
    processInfo.value.process = JSON.parse(data.processTemplates.process)
    processInfo.value.formJson = props.paramObj.processStatus === '4' ?
        JSON.parse(data.processTemplates.formItems) : getFormJson(detailVoMap[key][0].activityId, processInfo.value.process)
    processInfo.value.taskId = detailVoMap[key][0].taskId
        processInfo.value.formJson.forEach(item => {
      item.value = formData[item.id]
    })
  }
}

const init_Info = async () => {
  const paramObj = props.paramObj
  if (paramObj && ['1', '2', '4'].includes(paramObj.processStatus)) {//正在处理、撤销、结束的不显示暂存
    emits('update:hasTempSave', false)
    if (paramObj.processInstanceId) {// 存在流程实例、走流程审批
      //根据流程实例获取流程相关信息
      const res = await getInstanceInfo({processInstanceId: paramObj.processInstanceId})
      handleData(res)
      // 我的发起、已办禁止编辑
      if ([2, 4].includes(props.formType)) {
        processInfo.value.formJson.forEach(ele =>{
          ele.edit = false
        })
      }
    }
  } else if (paramObj && (paramObj.processStatus === '3')) {// 驳回不显示暂存
    //根据流程实例获取流程相关信息
    const res = await getInstanceInfo({processInstanceId: paramObj.processInstanceId})
    handleData(res)
    // 我的发起、已办禁止编辑
    if ([2, 4].includes(props.formType)) {
      processInfo.value.formJson.forEach(ele =>{
        ele.edit = false
      })
    }
    emits('update:hasTempSave', false)
  } else {// 草稿、新增
    const {code, data} = await getFlowDefinitionInfo(props.flowKey)
    if (code === 200) {
      processInfo.value.processDefinitionId = data.ProcessDefinitionId
      processInfo.value.process = data.Process
      processInfo.value.formJson = data.Process.props.formPerms
    }
    visible.value = true
  }
}

const getFormJson = (id, process) => {
  if (!process.children) return []
  return id === process.id ? process.props.formPerms : getFormJson(id, process.children)
}

// 暂存
const tempSave = ($event,$parent) => {
  // loading.value.tempLoading = true
  // flowFormRef.value.tempSave().then(res=>{
  //   if (res){
  //     $parent.init_PageQuery()
  //     visible.value = false
  //   }
  //   loading.value.tempLoading = false
  // }).catch(err =>{
  //   loading.value.tempLoading = false
  // })

}

// 提交
const startProcess = ($event,$parent) => {
  loading.value.startLoading = true
  const processData = {
    processDefinitionId: processInfo.value.processDefinitionId,
  }
  flowFormRef.value.startProcess(processData).then(res=>{
    if (res){
      visible.value = false
      $parent.init_PageQuery()
      ElMessage({message: '流程发起成功', type: 'success',})
    }
    loading.value.startLoading = false
  }).catch(err =>{
    loading.value.startLoading = false
  })
}

// 通过
const passProcess = ($event,$parent) => {
  loading.value.passLoading = true
  const processData = {
    taskId: processInfo.value.taskId,
    comments: commentData.value.comments,//意见
  }
  flowFormRef.value.passProcess(processData).then(res=>{
    if (res){
      visible.value = false
      $parent.init_PageQuery()
      ElMessage({message: '操作成功', type: 'success',})
    }
    loading.value.passLoading = false
  }).catch(err =>{
    loading.value.passLoading = false
  })
}

// 驳回
const refuseProcess = ($event,$parent) => {
  loading.value.refuseLoading = true
  const processData = {
    taskId: processInfo.value.taskId,
    comments: '',//意见
  }
  flowFormRef.value.refuseProcess(processData).then(res=>{
    if (res){
      visible.value = false
      $parent.init_PageQuery()
      ElMessage({message: '操作成功', type: 'success',})
    }
    loading.value.refuseLoading = false
  }).catch(err =>{
    loading.value.refuseLoading = false
  })
}

const init = () => {
  init_Info()
}
onMounted(()=> {
  init()
})
const component = modules[`/src/views/${props.componentUrl}.vue`].default
</script>

<template>
  <div class="flow-box">
    <v-dialog
        v-if="visible"
        :append-body="false"
        v-model="visible"
        :show-btn="false"
        :close-on-click-modal="false"
        :title="props.dialogTitle">

      <component ref="flowFormRef" :formJson="processInfo.formJson" :key="new Date().getTime()" :is="component" :paramObj="paramObj" />
      <div class="flow-detail-card">
        <el-card v-for="(node,index) in processInfo.auditedNodes" v-if="processInfo.auditedNodes.length > 0">
          <div class="inner-body" v-if="node.commentVoList.length !== 0">
            <div>流程节点：{{node.nodeName}}</div>
            <div v-for="(item, index) in node.commentVoList">
              审批意见： {{item.comments}}
            </div>
          </div>
        </el-card>
      </div>
      <div class="comment" v-if="paramObj.processInstanceId && ![2, 4].includes(formType)">
        <el-form :model="commentData" ref="commentRef" :rules="commentRules">
          <el-form-item label-width="20px" prop="comments">
            <el-input
                type="textarea"
                placeholder="请输入您的审批意见"
                :rows="4"
                v-model="commentData.comments"
                maxlength="100"
                show-word-limit
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="form-btn" >
        <el-button size="small" @click="visible = false" v-if="![2, 4].includes(formType)">取消</el-button>
        <el-button size="small" :loading="loading.tempLoading" v-if="hasTempSave" @click="tempSave($event,$parent)">暂存</el-button>
        <el-button type="primary" size="small"
                   :loading="loading.startLoading"
                   @click="startProcess($event,$parent)" v-if="!paramObj.processInstanceId && formType === 1">
          {{ loading.startLoading ? '提交中' : '提交' }}
        </el-button>
        <el-button type="primary" size="small"
                   :loading="loading.passLoading"
                   @click="passProcess($event,$parent)" v-if="paramObj.processInstanceId && ![2, 4].includes(formType)">
          通过</el-button>
        <el-button type="danger" size="small"
                   :loading="loading.refuseLoading"
                   @click="refuseProcess($event,$parent)" v-if="paramObj.processInstanceId && ![2, 4].includes(formType)">
          否决</el-button>
      </div>
    </v-dialog>
  </div>
</template>

<style scoped lang="scss">
.flow-box {

  .flow-detail-card {
    .el-card {
      margin-left: 20px;
      margin-bottom: 10px;
    }
    .inner-body {
      color: #999999;
    }
  }
  .comment {

  }
}
</style>